package com.qire.manhua.controller;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.CompoundButton;

import com.lzy.okgo.db.CacheManager;
import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.card.FloorCard;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.concurrent.Scheduler;
import com.qire.common.concurrent.ThreadUtil;
import com.qire.common.constant.DeviceConfigInfo;
import com.qire.common.constant.Navigation;
import com.qire.common.constant.TeensModeManage;
import com.qire.common.constant.Url;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.base.EventController;
import com.qire.common.support.base.ProxyViewModel;
import com.qire.common.utils.FileManager;
import com.qire.common.utils.ToastHelper;
import com.qire.common.widget.snackbar.Prompt;
import com.qire.manhua.activity.SystemSetupActivity;
import com.qire.manhua.activity.helper.LoginRouter;
import com.qire.manhua.dal.service.SystemSetupDataService;
import com.qire.manhua.databinding.ActivitySystemSetupBinding;
import com.qire.manhua.dialog.TeensPasswordAuthorizeDialog;
import com.qire.manhua.model.enumeration.TeensModeScene;
import com.qire.manhua.model.viewModel.ISystemSetupViewModel;

import androidx.annotation.NonNull;

public class SystemSetupController extends EventController<SystemSetupActivity> {

    private ProxyViewModel<ISystemSetupViewModel> viewModel;

    public SystemSetupController(@NonNull SystemSetupActivity lifecycleOwner) {
        super(lifecycleOwner);
    }

    @Override
    protected void bindView() {
        ActivitySystemSetupBinding viewDataBinder = owner.viewDataBinder();
        viewDataBinder.setSystemSetupController(this);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        this.viewModel = null;
    }

    public void onAddition(ProxyViewModel<ISystemSetupViewModel> viewModel) {
        this.viewModel = viewModel;
    }

    /*************************************************************************************************************************/

    /** 退出按钮事件响应 */
    public void backBtnOnClick(View view){
        owner.onBackPressed();
    }


    public void autoPayBtnOnClick(View view) {
        if(LoginRouter.ROUTER.checkLoginRouteIfNeed()) {
            return;
        }
        new SystemSetupDataService().toggleAutoPay(viewModel.getToValue("autoPay"));
    }
    public void autoPayBtnOnCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(LoginRouter.ROUTER.checkLoginRouteIfNeed()) {
            return;
        }
        // 后面的就是用户手动触发的情况
        viewModel.set("autoPay", isChecked);
    }


    /** 评价按钮事件响应 */
    public void evaluationBtnOnClick(View view){
        gotoRate();
    }
    private void gotoRate() {
        Uri uri = Uri.parse("market://details?id=" + owner.getPackageName());
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        try {
            owner.startActivity(goToMarket);
            new SystemSetupDataService().markEvaluation();
        } catch (ActivityNotFoundException e) {
            ToastHelper.showSnackBar("尚未安装应用市场，无法评分", Prompt.WARNING);
        }
    }


    private volatile boolean isClearing = false;
    /** 清除缓存按钮事件响应 */
    public void clearCacheBtnOnClick(View view) {
        if(isClearing) {
            return;
        }

        changeClearState(true);
        // 注意 postDelayed 是向handle消息队列投递消息处理，固即便是 Activity 退出 View 被销毁，这个消息任务依旧会被主 handle 执行。
        // 可以考虑使用 view.removeCallbacks(Runnable) 来删除，取消任务
        view.postDelayed(() -> changeClearState(false), 4000);

        ThreadUtil.once()
                .andThen(v -> FileManager.clearImageDiskCache())
                .schedulerBy(Scheduler.Main)
                .andThen(v -> viewModel.set("cacheCapacityHint", StringUtil.formatStorageSize(FileManager.countGlideCacheSize())))
                .accept();
    }
    /**
     * 改变清理状态，改方法
     * @param isClearing true 清理中， false 空闲
     */
    private void changeClearState(boolean isClearing) {
        this.isClearing = isClearing;
        if(ObjectUtil.nonNull(viewModel)) {
            // 这个方法由于使用了 view.postDelayed 来延时处理，固可能在执行到这里时 Activity 已经销毁,
            // 作为严谨回收考虑，在 {@link onCleared} 中会回收ViewModel，可能引起这里空指针异常，固做判空处理。
            viewModel.set("clearCacheClickable", !isClearing);
        }
    }


    /** 账户与安全按钮单击事件 */
    public void accountsAndSecurityBtnOnClick(View view) {
        AntsRouter.ROUTER.buildCard(Navigation.Page.AccountsAndSecurityPage).navigation();
    }


    /** 青少年模式按钮单击事件 */
    public void teensModeBtnOnClick(View view) {
        AntsRouter.ROUTER.buildCard(Navigation.Page.TeensControlPanelPage).navigation();
    }


    /** 消息设置按钮单击事件 */
    public void messageSetupBtnOnClick(View view) {
        AntsRouter.ROUTER.buildCard(Navigation.Page.MessageSetupPage).navigation();
    }


    /** 隐私条款按钮单击事件 */
    public void userAgreementBtnOnClick(View view) {
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.WebPage)
                .withData("title", "隐私条款")
                .withData("url", Url.privacyPolicy_url)
                .navigation();
        DeviceConfigInfo.savePrivacyProtocolVer();
    }


    /** 服务条款按钮单击事件 */
    public void serviceAgreementBtnOnClick(View view) {
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.WebPage)
                .withData("title", "服务条款")
                .withData("url", Url.serviceTerms_url)
                .navigation();
        DeviceConfigInfo.saveServiceProtocolVer();
    }

    /** 偏好收集按钮单击事件 */
    public void enablePreferencesOnCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(LoginRouter.ROUTER.checkLoginRouteIfNeed()) {
            return;
        }

        UserEntity.self.setEnablePreferences(isChecked);
        UserEntity.self.save();

        viewModel.set("enablePreferences", isChecked);
    }

    /** 退出或登录按钮单击事件 */
    public void logoutBtnOnClick(View view) {
        if(LoginRouter.ROUTER.checkLoginRouteIfNeed()) {
            return;
        }

        if(TeensModeManage.teensModeEnable()) {
            new TeensPasswordAuthorizeDialog(owner, TeensModeScene.Logout, this::onLogout).show();
        } else {
            onLogout();
        }
    }

    private void onLogout() {
        UserEntity.self.logout();
        CacheManager.getInstance().clear();
        owner.onBackPressed();
        // todo
//        activity.sendEvent(CustomEvent.EventTag_Logout);
    }

}
